package com.gbb.common.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * RecyclerView的适配器，提供点击及长按事件
 *
 * @param <T> 实体列表
 * @param <VH> 继承{@link RecyclerView.Adapter}
 */
public abstract class RecyclerViewAdapter<T,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {

	protected Context mContext;

	protected List<T> dataList;

	protected LayoutInflater mInflater;

	private OnItemClickListener<T> onItemClickListener;

	public RecyclerViewAdapter(Context mContext,List<T> dataList) {
		this.mContext = mContext;
		this.dataList = dataList;
		mInflater = LayoutInflater.from(this.mContext);
	}

	@Override
	public int getItemCount() {
		return dataList == null ? 0 : dataList.size();
	}

	@Override
	public abstract VH onCreateViewHolder(@NonNull ViewGroup parent,int viewType);

	@Override
	public void onBindViewHolder(@NonNull final VH holder,final int position) {
		if(onItemClickListener != null) {
			holder.itemView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					int position = holder.getLayoutPosition();
					onItemClickListener.onItemClick(holder.itemView,position,dataList.get(position));
				}
			});
			holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					int position = holder.getLayoutPosition();
					onItemClickListener.onItemLongClick(holder.itemView,position,dataList.get(position));
					return false;
				}
			});
		}
		onBindHolder(holder,position);
	}

	public abstract void onBindHolder(VH holder,int position);

	public void setOnItemClickListener(OnItemClickListener<T> listener) {
		this.onItemClickListener = listener;
	}

	public void add(int position,T t) {
		dataList.add(position,t);
		notifyItemInserted(position);
	}

	public void delete(int position) {
		dataList.remove(position);
		notifyItemRemoved(position);
	}

	public List<T> getDataList() {
		return dataList;
	}

	public void setDataList(List<T> dataList) {
		this.dataList = dataList;
		notifyDataSetChanged();
	}

	/**
	 * RecyclerView 未提供点击及长按事件
	 *
	 * @param <T> 泛型，点击项实体
	 */
	public interface OnItemClickListener<T> {

		void onItemClick(View view,int Position,T dataItem);

		void onItemLongClick(View view,int Position,T dataItem);

	}


}